﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace XPathAutoSuggest.Views {
    /// <summary>
    /// Code-Behind for Main Window
    /// </summary>
    /// <remarks>Most of the logic is in the ModelView class 'ModelView_MainWindow'; this
    /// class implements things that are difficult or impossible via MVVM</remarks>
    public partial class MainWindow : Window {
        private ModelView_MainWindow _vm;

        /// <summary>Default constructor hooks up the data context and an event</summary>
        public MainWindow() {
            InitializeComponent();
            XmlHelper xmlHelper = new XmlHelper();
            FileIOHelper fileIoHelper = new FileIOHelper();
            _vm = new ModelView_MainWindow(xmlHelper, fileIoHelper);
            _vm.CloseXmlForm += new CloseXmlFormEventHandler(_VM_CloseXmlForm);
            DataContext = _vm;
        }

        /// <summary>
        /// Fires after the window has loaded
        /// </summary>
        /// <param name="sender">The form</param>
        /// <param name="e">Event args</param>
        /// <remarks>
        /// Alas, this is not straightforward in MVVM, I have to do it in codebehind
        /// </remarks>
        private void Window_Loaded(object sender, RoutedEventArgs e) {
            //Help the user out and select some text for them; this will enable the Suggest button
            int p = _vm.FormattedXml.IndexOf("Learning XML");
            if (p >= 0)
                txtXml.Select(p, "Learning XML".Length);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <remarks>
        /// Why is this not bound to the ModelView to implement MVVM? Answer:
        /// "A 'Binding' cannot be set on the 'SelectionStart' property of type 'TextBox'. 
        /// A 'Binding' can only be set on a DependencyProperty of a DependencyObject."
        /// </remarks>
        private void txtXml_SelectionChanged(object sender, RoutedEventArgs e) {
            _vm.SelectionStart = txtXml.SelectionStart;
            _vm.SelectedXml = txtXml.SelectedText;
        }

        /// <summary>
        /// Event raised by our ModelView when user wants to close the form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void _VM_CloseXmlForm(object sender, EventArgs e) {
            this.Close();
        }
    }
}
